package com.ebt.m.customer.util;

import android.text.TextUtils;
import android.util.Log;

import com.ebt.m.AppContext;
import com.ebt.m.customer.model.BeanCustomerTapeWrapper;
import com.ebt.m.data.bean.BeanCustomerTape;
import com.ebt.m.data.greendao.BeanCustomerTapeDao;
import com.ebt.m.data.greendao.DaoMaster;
import com.ebt.m.data.greendao.DaoSession;

import org.greenrobot.greendao.query.DeleteQuery;
import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * Created by Rick.Wang on 2016/3/2.
 */
public class RecordManager {

    private static RecordManager instance;

    private AppContext mAppContext;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private BeanCustomerTapeDao mBeanCustomerTapeDao;

    private RecordManager() {
    }

    public static RecordManager getInstance() {
        if (instance == null) {
            synchronized (RecordManager.class) {
                if (instance == null) {
                    instance = new RecordManager();
                }
            }
        }
        return instance;
    }

    public RecordManager setAppContext(AppContext appContext) {
        if (appContext == null) {
            throw new IllegalArgumentException("AccountManager setAppContext()'s argc is null.");
        }
        if (mAppContext == null) {
            mAppContext = appContext;
        }
        return this;
    }

    public AppContext getAppContext() {
        if (mAppContext == null) {
            throw new IllegalArgumentException("AccountManager getContext() == null. have you set setContext() for AccountManager before?");
        }
        return mAppContext;
    }

    public BeanCustomerTapeDao getBeanCustomerTapeDao() {
        if (mDaoMaster == null) {
            mDaoMaster = getAppContext().getDaoMaster();
        }
        if (mDaoSession == null) {
            mDaoSession = mDaoMaster.newSession();
        }
        if (mBeanCustomerTapeDao == null) {
            mBeanCustomerTapeDao = mDaoSession.getBeanCustomerTapeDao();
        }
        return mBeanCustomerTapeDao;
    }

    /**
     * 获取NoteUuid中包含的所有的tape
     *
     * @param noteUuid
     * @return
     */
    public List<BeanCustomerTape> getBeanCustomerTapes(String noteUuid) {
        return getBeanCustomerTapeDao().queryBuilder()
                .where(BeanCustomerTapeDao.Properties.FilePath.isNotNull(),
                        BeanCustomerTapeDao.Properties.NoteUuid.eq(noteUuid))
                .orderDesc(BeanCustomerTapeDao.Properties.CreateTime)
                .list();
    }

    /**
     * 向数据库增加一个BeanCustomerTape实体类
     *
     * @param customerTape
     * @return
     */
    public long addBeanCustomerTape(BeanCustomerTape customerTape) {

        if (customerTape.getUuid() == null) {
            customerTape.setUuid(UUID.randomUUID().toString());
        }

        if (customerTape.getCreateTime() == null) {
            customerTape.setCreateTime(new Date());
        }

        return getBeanCustomerTapeDao().insertOrReplace(customerTape);
    }

    /**
     * 删除NoteUuid对应的所有的tape
     *
     * @param noteUuid
     */
    public void deleteBeanCustomerTapeByNoteUuid(String noteUuid) {

        if (TextUtils.isEmpty(noteUuid)) return;

        QueryBuilder<BeanCustomerTape> qb = getBeanCustomerTapeDao().queryBuilder();
        DeleteQuery<BeanCustomerTape> dq = qb.where(BeanCustomerTapeDao.Properties.NoteUuid.eq(noteUuid))
                .buildDelete();
        dq.executeDeleteWithoutDetachingEntities();
    }

    /**
     * 删除一个CustomerTape
     *
     * @param tapeUuid
     */
    public void deleteBeanCustomerTapeByTapeUuid(String tapeUuid) {

        if (TextUtils.isEmpty(tapeUuid)) return;

        QueryBuilder<BeanCustomerTape> qb = getBeanCustomerTapeDao().queryBuilder();
        DeleteQuery<BeanCustomerTape> dq = qb.where(BeanCustomerTapeDao.Properties.Uuid.eq(tapeUuid))
                .buildDelete();
        dq.executeDeleteWithoutDetachingEntities();

    }

    /**
     * 处理最后获取的 BeanCustomerTapeWrapper list
     *
     * @param tapeWrappers
     */
    public void operateResultTapeWrappers(ArrayList<BeanCustomerTapeWrapper> tapeWrappers) {
        if (tapeWrappers == null) return;
        for (BeanCustomerTapeWrapper tapeWrapper : tapeWrappers) {
            switch (tapeWrapper.getState()) {
                case ORIGINAL:
                    continue;
                case ADD:
                    addBeanCustomerTape(tapeWrapper.getTape());
                    break;
                case DELETE:
                    Log.d("tape", "operateResultTapeWrappers should not have delete tape!");
                    deleteBeanCustomerTapeByTapeUuid(tapeWrapper.getTape().getUuid());
                    deleteTapeFile(tapeWrapper.getTape().getFilePath());
                    break;
            }
        }
    }

    public void deleteResultTapeWrappers(ArrayList<BeanCustomerTapeWrapper> tapeWrappers) {
        if (tapeWrappers == null) return;
        for (BeanCustomerTapeWrapper tapeWrapper : tapeWrappers) {
            switch (tapeWrapper.getState()) {
                case ADD:
                    break;
                case ORIGINAL:
                    deleteBeanCustomerTapeByTapeUuid(tapeWrapper.getTape().getUuid());
                    deleteTapeFile(tapeWrapper.getTape().getFilePath());
                    break;
                case DELETE:
                    Log.d("tape", "operateResultTapeWrappers should not have delete tape!");
                    deleteBeanCustomerTapeByTapeUuid(tapeWrapper.getTape().getUuid());
                    deleteTapeFile(tapeWrapper.getTape().getFilePath());
                    break;
            }
        }
    }

    public boolean deleteTapeFile(String path) {
        File file = new File(path);
        if (!file.exists()) return true;
        return file.delete();
    }

    /**
     * 批量更新tape
     */
    public void updateTapes(List<BeanCustomerTape> list) {
        getBeanCustomerTapeDao().updateInTx(list);
    }

}